package com.cf.web.controller;

import com.cf.constant.EnumReturnCode;
import com.cf.exception.BizStackException;
import com.cf.util.ReflectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * boot-awm-MvcHandlers
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/7/6 上午 11:18
 */
@Slf4j
public class MvcHandlers {


    @Autowired(required = false)
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    public HandlerMethod handler(HttpServletRequest request) throws BizStackException {
        if (requestMappingHandlerMapping == null)
            throw new BizStackException(EnumReturnCode.ERROR.getCode(), "当前环境非web环境，无法使用！");
        try {
            Method lookupHandlerMethod = ReflectionUtil.getAccessibleMethodByName(requestMappingHandlerMapping, "lookupHandlerMethod");
            String requestURI = request.getRequestURI();
            lookupHandlerMethod.setAccessible(true);
            return (HandlerMethod) lookupHandlerMethod.invoke(requestMappingHandlerMapping, requestURI, request);
        } catch (Exception e) {
            log.warn("外找到url对应的handler,返回null");
            return null;
        }
    }


    public boolean isJsonResponse(HttpServletRequest request) throws BizStackException {
        HandlerMethod handler = handler(request);
        if (handler == null) {
            return true;
        }
        Method method = handler.getMethod();
        if (method.getAnnotation(ResponseBody.class) != null) {
            return true;
        }

        if (handler.getBeanType().getAnnotation(RestController.class) != null || handler.getBeanType().getAnnotation(ResponseBody.class) != null) {
            return true;
        }

        return false;
    }
}
